var path = require('path');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var winston = require('winston');
var utils = require('../lib/utils');
var mysql = require('mysql');

var myQuery = function(connection, queryString){
	return new Promise(function(resolve, reject){
		connection.query(queryString, function(err, rows){
			if(err){
				reject(err);
			}else{
				resolve(rows);
			}
		});
	});
};
var luckyRecord = function(connection, queryString){ 
	myQuery(connection, queryString)
		.then(function(){ 
			connection.release();	
		})
		.catch(function(err){ 
			connection.release();
			winston.error(err);
		});
};
module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var queryWinners = 'SELECT COUNT(*) as winners FROM luckydraw WHERE state="win" AND event_id=' + eventId;
	var pathToConfig = path.join(__dirname, '..', 'events', eventId, 'config.json');
	var results = { 
		lucky:false,
		level:null
	};
	if(fs.existsSync(pathToConfig)){ 
		var config = require(pathToConfig);
		var probability = config.probability || 0.01;
		var win = utils.luckyDraw(probability);
		winston.info(config, probability, win);

			pool.getConnection(function(err, connection){ 
				if(err){ 
					winston.error(err);
					res.send(results);
				}else{ 
					var queryRecord = 'INSERT INTO luckydraw (event_id, random_code, timestamp, state, level, price) VALUES ( ?, ?, ?, ?, ?, ? )';	
					var params = [eventId, utils.generateRandomCode(), String.from(Date.now())];
					if(win){ 
						myQuery(connection, queryWinners)
							.then(function(rows){ 
								if(rows[0]['winners'] >= config.limits){ 
									params = params.concat(['loose', null, null]);
									luckyRecord(connection, mysql.format(queryRecord, params));
									res.send(results);
								}else{
									params = params.concat(['win', '1', 'normal']);
									luckyRecord(connection, mysql.format(queryRecord, params));
									results.lucky = true;
									results.level = 1;
									res.send(results);
								}
							})
							.catch(function(err){ 
						winston.info('err on get winners');
								winston.error(err);
								params = params.concat(['loose', null, null]);
								luckyRecord(connection, mysql.format(queryRecord, params));
								res.send(results);
							});
					}else{
						params = params.concat(['loose', null, null]);
						luckyRecord(connection, mysql.format(queryRecord, params));
						res.send(results);
					}
				}
			});
	}else{ 
		res.send('bad event id.');
	}
	
}
